// ignore_for_file: unnecessary_null_comparison, use_build_context_synchronously

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tiktokadult/hj_utils/api_service/ai_service.dart';
import 'package:tiktokadult/hj_utils/global.dart';

import '../../../../hj_model/upload_video_model.dart';
import '../../../../tools_base/file_upload/file_upload_tool.dart';
import '../../../../tools_base/global_store/store.dart';
import '../../../../tools_base/loading/loading_alert_widget.dart';
import '../../../alert_business/mine/vip_level_dialog.dart';
import '../../../alert_business/normal_alert_style.dart';
import 'ai_main_record_page.dart';

class AiLogic extends GetxController with GetTickerProviderStateMixin {
  final int tabIndex; //0-视频换脸 1-图片换脸 2-ai脱衣
  AiLogic(this.tabIndex);

  late TabController tabCtr;

  bool isShowLoading = true;

  UploadVideoModel uploadModel = UploadVideoModel();

  String? selectedImagePath;

  @override
  void onInit() {
    super.onInit();
    tabCtr = TabController(
      initialIndex: tabIndex,
      length: 3,
      vsync: this,
    );
  }

  toAiRecord(BuildContext context) {
    int position = 0;
    if (tabCtr.index == 0) {
      position = 1;
    } else if (tabCtr.index == 1) {
      position = 2;
    } else if (tabCtr.index == 2) {
      position = 0;
    }
    Get.to(AIMainRecordPage(position: position));
  }

  submitAiImage(BuildContext context) async {
    if (!globalStore.isVIP()) {
      showVipLevelDialog("您还不是VIP无法使用AI脱衣");
      return;
    }
    if (uploadModel.localPicList.isEmpty) {
      showConfirm(title: "提示", content: "请选择图片");
      return;
    }
    List<String> picList = uploadModel.localPicList;

    LoadingAlertWidget.show();
    try {
      LoadingAlertWidget.showExchangeTitle("正在上传图片...");
      var uploadImgArr = await FileUpLoadTool().uploadImageList(picList, proCallback: (
        tIndex,
        tAll,
        proCount,
        totalCount,
      ) {
        LoadingAlertWidget.showExchangeTitle(
          "正在上传图片${(100 * (proCount / totalCount / tAll + tIndex / tAll)).toStringAsFixed(1)}%",
        );
      });
      List<String> imageArr = [];
      if (uploadImgArr?.isNotEmpty == true) {
        imageArr = uploadImgArr!.map((e) => e.coverImg ?? "").toList();
      }
      LoadingAlertWidget.showExchangeTitle("正在更新数据...");

      bool result = await AIService.aiGenerate(imageArr);

      if (result) {
        showToast("提交成功～");
        uploadModel.localPicList.clear();
        uploadModel.selectedTagIdList.clear();
        selectedImagePath = null;
      } else {
        showToast("提交失败");
      }
    } on DioException catch (e) {
      showToast(e.message.toString());
    } catch (e) {
      showToast(e.toString());
    } finally {
      LoadingAlertWidget.cancel();
    }
  }
}
